<?php

namespace app\admin\controller\crm;

use app\common\controller\Backend;
use think\Db;
use think\Session;
/**
 * 公海客户
 *
 * @icon fa fa-circle-o
 */
class Highseas extends Backend
{
    
    /**
     * Highseas模型对象
     * @var \app\admin\model\Highseas
     */
    protected $model = null;
    protected  $admin_data = array();
    public function _initialize()
    {
        parent::_initialize();
        $this->searchFields = 'buser.username,admin.nickname,admin.username';
        $this->model = new \app\admin\model\Highseas;
        $adminData = Session::get("admin");
        $linkAdmin = Db::name('Admin');
        $this->admin_data = $linkAdmin->field('a.*,g.id AS gid,g.name,g.pid')->alias('a')->join('fa_auth_group_access u','a.id = u.uid','LEFT')
            ->join('fa_auth_group g','u.group_id = g.id','LEFT')
            ->where(array('a.id'=>$adminData['id']))->find();
        $statusData = $this->model->getStatusList();
        $this->view->assign('statusData',$statusData);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 网贷客户公海
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['buser','product','admin','allot'])
                    ->where($where)
                    ->where(array('allot.status'=>array('NOT IN',6),'allot.userlist'=>'1','highseas.userlist'=>'1'))
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with(['buser','product','admin','allot'])
                    ->where($where)
                    ->where(array('allot.status'=>array('NOT IN',6),'allot.userlist'=>'1','highseas.userlist'=>'1'))
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->visible(['createtime','reason','buser_id','product_id']);
                $row->visible(['buser']);
				$row->getRelation('buser')->visible(['username','contacts','qq','wechat','mobile','email']);
				$row->visible(['product']);
				$row->getRelation('product')->visible(['product']);
				$row->visible(['admin']);
				$row->getRelation('admin')->visible(['nickname']);
				$row->visible(['allot']);
				$row->getRelation('allot')->visible(['id','status']);
            }
            $list = collection($list)->toArray();
            $linkAllot = Db::name('Allot');
            foreach ($list as $k=>$v){
                $allotData = $linkAllot->where(array('admin_id'=>$this->admin_data['id'],'buser_id'=>$v['buser_id'],'product_id'=>$v['product_id'],'userlist'=>'1'))->find();
                if($allotData){
                    $list[$k]['type'] = 'hide';
                }else{
                    $list[$k]['type'] = 'show';
                }
                $list[$k]['id'] = $v['allot']['id'];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     * 适用于所有类型的客户
     */
    public function add($ids=null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $linkAllot = Db::name('Allot');
                $allotData = $linkAllot->where(array('id'=>$ids))->find();
                if(!$allotData){
                    $this->error('不存在的分配数据');
                }
                //检查数据是否已经投过公海
                $gongData = $this->model->where(array('allot_id'=>$ids))->find();
                if($gongData){
                    $this->error('当前数据已经投放过公海');
                }
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['buser_id'] = $allotData['buser_id'];
                    $params['product_id'] = $allotData['product_id'];
                    $params['admin_id'] = $allotData['admin_id'];
                    $params['allot_id'] = $ids;
                    $params['userlist'] = ''.$allotData['userlist'].'';
                    $result = $this->model->allowField(true)->save($params);
                    //修改公海状态
                    $save = $linkAllot->where(array('id'=>$ids))->update(array('highlist'=>'2'));
                    if ($result !== false&&$save!==false) {
                        Db::commit();
                        $this->success();
                    } else {
                        Db::rollback();
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 挑入分配管理
     * 适用于所有类型的客户
     */
    public function pick($ids=null){
        $linkAllot = new \app\admin\model\Allot();
        $row = $linkAllot->where(array('id'=>$ids,'status'=>array('NOT IN','6')))->find();
        if (!$row){
            $this->error(__('No Results were found'));
        }
        $user_verification=false;
        $this->user_verification($this->admin_data['pid'],'销售部',$user_verification);//判断是否是销售部门
        if(!$user_verification){
            $this->error('您不是销售部的小伙伴,不能挑入数据');
        }
        $allotData = $linkAllot->where(array('admin_id'=>$this->admin_data['id'],'buser_id'=>$row['buser_id'],'product_id'=>$row['product_id'],'userlist'=>''.$row['userlist'].''))->find();
        if($allotData){
            $this->error('您已经存在当前客户的分配数据');
        }
        //查询期限时间
        $qi = Db::name('allot_expire')->where(array('id'=>2))->value('expire');
        $allot_date = date('Y-m-d H:i:s',time());
        $expire_date = date('Y-m-d H:i:s',strtotime('+'.$qi.' days'));
        $fieldArray = array(
            'buser_id'=>$row['buser_id'],
            'admin_id'=>$this->admin_data['id'],
            'product_id'=>$row['product_id'],
            'expire_date'=>$expire_date,
            'allot_date'=>$allot_date,
            'userlist'=>''.$row['userlist'].'',
            'status'=>''.$row['status'].''
        );
        try {
            //是否采用模型验证
            $add = $linkAllot->insertGetId($fieldArray);
            if($add){
                //挑入成功
                $this->success('挑入成功');
            }else{
                $this->error($linkAllot->getError());
        }
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->error($e->getMessage());
        }
    }
    /**
     * 批量挑入
     * $ids :allot表主键id
     * 适用于所有类型的客户
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                if (!$this->auth->isSuperAdmin()) {
                    $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                }
                if ($values) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    $user_verification=false;
                    $this->user_verification($this->admin_data['pid'],'销售部',$user_verification);//判断是否是销售部门
                    if(!$user_verification){
                        $this->error('您不是销售部的小伙伴,不能挑入数据');
                    }
                    $admin_id = $this->admin_data['id'];//销售ID
                    $linkAllot = Db::name('Allot');
                    $list = $linkAllot->where(array('id'=>array('IN',$ids,'status'=>array('NOT IN','6'))))->select();
                    if(!$list){
                        $this->error('不存在的分配数据');
                    }
                    //查询期限时间
                    $qi = Db::name('allot_expire')->where(array('id'=>2))->value('expire');
                    $allot_date = date('Y-m-d H:i:s',time());
                    $expire_date = date('Y-m-d H:i:s',strtotime('+'.$qi.' days'));
                  /*  $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();*/
                     $add = false;
                     Db::startTrans();
                    foreach ($list as $index => $item) {
                        //检查当前销售员工是否在追踪相同的数据
                        $admin_con = $linkAllot->where(array('admin_id'=>$admin_id,'buser_id'=>$item['buser_id'],'product_id'=>$item['product_id'],'userlist'=>''.$item['userlist'].''))->find();
                        if(!$admin_con){
                            $field = array(
                                'buser_id'=>$item['buser_id'],
                                'admin_id'=>$admin_id,
                                'product_id'=>$item['product_id'],
                                'allot_date'=>$allot_date,
                                'expire_date'=>$expire_date,
                                'status'=>''.$item['status'].'',
                                'userlist'=>''.$item['userlist'].''
                            );
                            $add = $linkAllot->insertGetId($field);
                            if($add){
                                $add = true;
                            }else{
                                $add = false;
                                Db::rollback();
                                $this->error(__('挑入失败'));
                            }
                        }else{
                            $add = false;
                            Db::rollback();
                            $this->error('不能挑入您已经存在的客户数据');
                        }
                    }
                    if ($add) {
                        Db::commit();
                        $this->success();
                    }else{
                        Db::rollback();
                        $this->error('操作失败');
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
